function makeTableRow(o, cols, addCols,formatFun) {
    colList = cols.split(",");
    r = "<tr>";
    for (c of colList) {
        let v = o[c];
        if(v==null){
            v=eval('o.'+c);
            /*
            if(c.indexOf(".")!=-1){
                let parts = c.split(".");
                let po=o;
                for(p of parts){
                    po=po[p];
                    if(!po) break;
                }
                if(po){
                    v=po;
                }
            }
            */
        }
        if(formatFun){
            let vf = formatFun(c,v,o);
            if(vf!=undefined&&v!=null){
                v=vf;
            }
        }
        
        if(v===null) v='';
        if (c.toLowerCase().endsWith("url")
            || v instanceof String && v.startsWith("http")) {
            if (!v.startsWith("http")) {
                v = "http://" + v;
            }
            v = "<a href = '" + v + "' target='_blank'>" + v + "</a>";
        }
        r += "<td>" + v + "</td>"
    }
    r += addCols;
    r += "</tr>"
    return r;
}

function makeTableBody( data,cols="name",colFun,tableId='#mainTable',formatFun){

    $table = $(tableId);
    $(tableId+ " > tbody > tr").remove();

    $tbody = $(tableId+ " > tbody");
    for (var v of data) {
        row = makeTableRow(v,cols ,colFun(v),formatFun);
        $tbody.append(row);
    }
}

function getJQObj(idOrForm){
    var $form=idOrForm;
    if(typeof(idOrForm) === 'string'){
        $form=$(`#${idOrForm}`);
    }

    return $form;
}

function setInputVals(idOrForm,obj){
   $form = getJQObj(idOrForm);
   $form.find("input[name],select[name]").each(function(){
    var $this=$(this);
    var name=$this.attr('name');
    if(!name) return;
    var v=obj[name];
    if(v===undefined){
        v=eval('obj.'+name);
    }
    if(v!=undefined){
        $this.val(v);
    }
    
   });
}

function getInputVals(idOrForm){
    var $form=idOrForm;
    if(typeof(idOrForm) === 'string'){
        $form=$(`#${idOrForm}`);
    }
    var reqData={};
    $form.find("input[name],select[name]").each(function(i){
        var $this=$(this);
        var val=$this.val();
        if($this.attr("type")==="checkbox"){
            val=this.checked;
        }
        reqData[$this.attr('name')]=val;
    });
    return reqData;
}

function getInputValsArray(selOrObj){
    let datas=[];
    let $ts=null;
    if(typeof(selOrObj)==='string'){
        $ts=$(selOrObj);
    }
    else{
        $ts=selOrObj;
    }
    $ts.each(function(){
        obj=getInputVals($(this));
        datas.push(obj);
    });
    return datas;
}

function log(m){
    console.log(m);
}

function showMsg(msg){
    if (!(msg instanceof String)){
        msg=JSON.stringify(msg);
    }
    $('#msg').text(msg);
}

function postJson(url,data,fun,errFun){
    $.ajax({
        "url": url
        , type: "POST"
        ,data:JSON.stringify(data)
        ,success:fun
        ,error:errFun || fun
        ,headers :{ 'content-type': 'application/json'}

    })
}

function convertDotProperties(data){
    if(Array.isArray(data)){
        for (var v of data){
            convertDotProperties(v);
        }
        return;
    }
    for (var p in data){
        if(p.indexOf('.')>0){
            v=data[p];
            parts = p.split('.');
            let cdata=data;
            for(let i=0;i<parts.length-1;i++){
                let pt=parts[i];
                if(!cdata[pt]){
                    cdata[pt]={};
                }
                cdata=cdata[pt];
            }
            cdata[parts[parts.length-1]]=v;
        }
    }
}

function convertDotPropertiesBack(data){
    for (var p in data){
        v=data[p];
        if(v instanceof Object){
            //todo
        }
    }
}

function genSelect(name,data,val){

    opts='';
    for(let o of data){
        isSel='';
        if(val == o.id){
            isSel='selected'
        }
        opts+=`<option value=${o.id} ${isSel}>${o.name}</option>\n`;
    }


    return  `
    <select name="${name}">${opts}</select>
    `
}

function genInput(name,val,type="text"){

    addPros="";
    if(name==id){
        addPros+=" disabled ";
    }

    return `
    <div>
        <label  class="form-label" for="${name}-id" >${name}</label>
        <input class="form-control" id=""${name}-id" name="${name}" type="${type}" ${addPros}>
    </div>
    `
}

function genForm(id,colsOrObj,colTypeMaping={},cls=''){
    var obj={};
    if(typeof(colsOrObj) == 'string'){
        var cols = colsOrObj.split(',');
        for(var c of cols){
            c=c.trim();
            obj[c]='';
        }
    }
    else{
        obj=colsOrObj;
    }

    var html=`<div class='${cls}' id='${id}'>`



    for(var name in obj){
        html+=genInput(name,obj[name],colTypeMaping[name]);
    }

    html+="</div>"

    return html;
}

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}
